package sysmap

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/ecomp-analyzer-services/consts"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/dao"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/model"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/exception"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/tools"
	"github.com/gogf/gf/v2/frame/g"
)

// GetValueList 获取字典值列表
func (m *sSysMap) GetValueList(ctx context.Context, name string) (rows []model.SysMapValueListItem, err error) {
	rows = []model.SysMapValueListItem{}
	// 获取数据
	err = m.ValueModel().Scan(ctx, g.Map{
		dao.SysMapValue.Columns().Name: name,
	}, &rows)
	return
}

// GetValueDetail 获取字典值详情
func (m *sSysMap) GetValueDetail(ctx context.Context, id uint) (detail *model.SysMapValueDetailItem, err error) {
	detail = &model.SysMapValueDetailItem{}
	// 获取详情
	err = m.ValueModel().DetailPri(ctx, id, &detail)
	return
}

// GetMapAll 获取所有字典组值
func (m *sSysMap) GetMapAll(ctx context.Context, isRefresh ...bool) (map[string]map[string]string, error) {
	var (
		rows      []model.SysMapValueAttrItem
		valueMap  = make(map[string]map[string]string)
		cacheKey  = tools.CacheKey(consts.SysMapGroup)
		cacheFunc = func(ctx context.Context) (interface{}, error) {
			// 获取字典值列表
			err := m.ValueModel().Scan(ctx, g.Map{}, &rows)
			if err != nil {
				return nil, exception.New(`暂无字典数据`)
			}

			// 是否存在
			if len(rows) == 0 {
				return nil, exception.New(`字典值不存在`)
			}
			return rows, nil
		}
	)

	// 是否强制刷新
	if len(isRefresh) > 0 && isRefresh[0] == true {
		_, _ = sredis.NewCache().Remove(ctx, cacheKey)
	}

	// 缓存-永久存储
	r, err := sredis.NewCache().GetOrSetFunc(ctx, cacheKey, cacheFunc, 0)
	if err != nil {
		return nil, err
	}

	// 转换为列表类型
	if err = r.Structs(&rows); err != nil {
		return nil, exception.New(`转换字典值失败%s`, err.Error())
	}

	// 迭代处理字典
	for _, item := range rows {
		valMap, ok := valueMap[item.Name]
		if !ok {
			valMap = make(map[string]string)
		}
		valMap[item.Value] = item.Explain
		valueMap[item.Name] = valMap
	}
	return valueMap, nil
}
